package com.example.activity;

import android.app.Application;
import android.os.Bundle;
import android.widget.Toast;

import com.example.application.BaseActivity;
import com.example.application.MyApplication;
import com.example.db.DBService;
import com.example.piechartview.OnDateChangedLinstener;
import com.example.piechartview.StatisticsView;

import java.util.Calendar;
import java.util.HashMap;

public class CountActivity extends BaseActivity implements OnDateChangedLinstener, StatisticsView.OnTriggerClickListener {
    private StatisticsView mView;

    private DBService dbService;
    private MyApplication myApp;
    private boolean mState = true;//是否为支出 收入2  支出 1
    private int year;
    private int month;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dbService = new DBService(this);
        myApp = (MyApplication) getApplication();

        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH)+1;
        initData(2);
    }
    private void initData(int state){
        String timeFlag = year+"";
        if(month>=10){
            timeFlag = timeFlag+month;
        }else{
            timeFlag = timeFlag+"0"+month;
        }
        HashMap<String, Float> map = dbService.findCountByName(myApp.getUserName(), state + "",timeFlag);
        float[] items = new float[map.size()];
        String[] types = new String[map.size()];
        int total = 0;
        int i = 0;
        for (String typeName:map.keySet()){
            types[i] = typeName;
            items[i] = map.get(typeName);
            total += items[i];
            i++;
        }
        mView = new StatisticsView(this, items, total, types,this);
        if(mState){
            mView.setShowInfo("本月共收入"+total+"元");
        }else{
            mView.setShowInfo("本月共消费"+total+"元");
        }
        mView.setCurrDate(year, month);
        mView.setDateChangedListener(this);
        setContentView(mView);
    }

    public void onDateChanged(String startDate, String endDate) {
        String[] temp = startDate.split("-");
        if(temp.length>=2){
            year = Integer.parseInt(temp[0]);
            month = Integer.parseInt(temp[1]);
        }
        if (mState){
            initData(2);
        }else{
            initData(1);
        }
    }

    @Override
    public void OnTriggerClickListener() {
        mState = !mState;
        if (mState){
            initData(2);
        }else{
            initData(1);
        }
    }
}
